﻿/*************************************************
taurus 网络监听/心跳
author：Daixiwei
**************************************************/
using System;
using System.Collections.Generic;
using System.Timers;

namespace taurus.client
{
    public class LagMonitor
    {
        private int _averagePingTime;
        private Timer _pollTimer;
        private int _queueSize;
        private SocketEngine _engine;
        private List<int> _valueQueue;

        public LagMonitor(SocketEngine engine, int interval, int queueSize)
        {
            if (interval < 1)
            {
                interval = 1;
            }
            _engine = engine;
            _valueQueue = new List<int>();
            _queueSize = queueSize;
            _pollTimer = new Timer();
            _pollTimer.Enabled = false;
            _pollTimer.AutoReset = true;
            _pollTimer.Elapsed += new ElapsedEventHandler(__OnPollEvent);
            _pollTimer.Interval = interval * 1000;
            _averagePingTime = 1000;
        }

        Queue<long> write_queue = new Queue<long>();

        void __OnPollEvent(object source, ElapsedEventArgs e)
        {
            _engine._controller.sendPingPong();
            write_queue.Enqueue(DateTime.Now.Ticks);
        }

        public void fnPingPong()
        {
            var w_time =  write_queue.Dequeue();
            var item = DateTime.Now.Ticks - w_time;
            if (_valueQueue.Count >= _queueSize)
            {
                _valueQueue.RemoveAt(0);
            }
            _valueQueue.Add((int)(item / 10000));
            if (_valueQueue.Count == 0)
            {
                _averagePingTime = 0;
            }
            int num = 0;
            for (int i = 0; i < _valueQueue.Count; ++i)
            {
                num += _valueQueue[i];
            }
            _averagePingTime = (num / _valueQueue.Count);
        }

        /// <summary>
        /// 启动监听
        /// </summary>
        public void start()
        {
            if (!isRunning())
            {
                _pollTimer.Start();
                __OnPollEvent(null,null);
            }
        }

        /// <summary>
        /// 停止监听
        /// </summary>
        public void stop()
        {
            if (isRunning())
            {
                _pollTimer.Stop();
            }
        }

        public void destroy()
        {
            stop();
            _pollTimer.Dispose();
            _pollTimer = null;
            _engine = null;
        }

        /// <summary>
        /// 平均Ping的时间
        /// </summary>
        public int getAveragePingTime()
        {
            return _averagePingTime;
        }

        public bool isRunning()
        {
            return _pollTimer.Enabled;
        }
    }
}
